import 'package:flutter/material.dart';
import 'package:vdrag_saas/api.dart';
import 'package:vdrag_saas/bus.dart';
import 'package:vdrag_saas/list/pages/home/components/type_link.dart';

class ProductType extends StatefulWidget {
  // Function onSearch;
  const ProductType({super.key});
  @override
  State<StatefulWidget> createState() => _ProductType();
}

class _ProductType extends State<ProductType> {
  late Future<List<String>> _requestData;
  List<String> initData = ['全部', '油气'];
  List<TypeLink> _list = [];
  bool hasInit = false;
  void onSelect(TypeLinkState type) {
    if (Global.defaultType != type) {
      Global.defaultType!.unselect();
      type.select();
      Global.defaultType = type;
      Global.type = type.text;
      Global.searchTagKey.currentState?.onChange();
    }
  }

  Future<List<String>> requestData() async {
    return await Api.listTypes();
  }

  List<TypeLink> buildType(List<String> items) {
    if (hasInit && _list.length > 1) {
      return _list;
    }
    hasInit = true;
    List<TypeLink> list = [];
    TypeLink first = TypeLink(
      '全部',
      selected: true,
      callback: onSelect,
    );
    list.add(first);
    for (var item in items) {
      list.add(TypeLink(
        item,
        callback: onSelect,
      ));
    }
    _list = list;
    return list;
  }

  @override
  void initState() {
    // TODO: implement initState
    _requestData = requestData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        initialData: initData,
        future: _requestData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          List<String> appData = [];
          if (snapshot.connectionState == ConnectionState.done) {
            if (!snapshot.hasError) {
              appData = snapshot.data;
            }
          }
          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: buildType(appData),
            ),
          );
        });
  }
}
